package cn.minsh.lims.eoms.modules.app.handler;

import com.baomidou.mybatisplus.extension.api.R;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@ControllerAdvice
@ResponseBody
public class GlobleExceptionHandler {

    /**
     * 要拦截的异常Exception
     */
    @ExceptionHandler(value = Exception.class)
    public R exceptionHandler(Exception e) {

        if (e instanceof BindException) {
            e.printStackTrace();
            BindException ex = (BindException) e;
            List<ObjectError> allErrors = ex.getAllErrors();
            ObjectError objectError = allErrors.get(0);
            String ms = objectError.getDefaultMessage();
            return R.failed(ms);
        } else {
            e.printStackTrace();
            return R.failed(e.getMessage());
        }
    }
}
